import cv2
import os
recognierPath = './recognizer/haarcascades/haarcascade_frontalface_alt2.xml'


def detectFace(img):
    '''
    人脸检测
    :param img:
    :return: 检测到的人脸的 bbox(x,y,w,h)
    '''
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    face_detector = cv2.CascadeClassifier(recognierPath)
    facesLocations = face_detector.detectMultiScale(img)
    return facesLocations

def detectOneFace(img):
    '''
    从图像中检测一张人脸
    :param img:
    :return:
    '''
    res = detectFace(img)

    maxArea=-1
    maxAreaIndex=-1
    if len(res)>1:
        for index,( x,y,w,h) in enumerate(res):
            area=w*h
            if area>maxArea:
                maxArea=area
                maxAreaIndex=index
        return [res[0]]
    return res



def drawBox(facesLocations, img, names=[]):
    '''
    绘制人脸框
    :param facesLocations: 人脸bbox
    :param img: 原始图像
    :param names: 每个bbox对应的人脸的label
    :return:null
    '''
    for index, (x, y, w, h) in enumerate(facesLocations):
        cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255))

        # FONT_HERSHEY_PLAIN
        # FONT_HERSHEY_SIMPLEX
        if len(names) > 0:
            font = cv2.FONT_HERSHEY_SIMPLEX
            textSize = cv2.getTextSize(names[index], font, 1, 2)
            cv2.rectangle(img, (x, y - textSize[0][1] - textSize[1] - 1), (x + textSize[0][0], y), (0, 0, 255), -1)
            cv2.putText(img, names[index], (x, y - textSize[1]), font, 1, (255, 255, 255), 2)


